<template>
  <div class="insure-management">
    <!-- 搜索和操作区域 -->
    <div class="operation-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="姓名">
          <el-input
            v-model="queryParams.insureName"
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input
            v-model="queryParams.idCard"
            placeholder="请输入身份证号"
            clearable
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            v-model="queryParams.sex"
            placeholder="请选择性别"
            clearable
            style="width: 100px"
          >
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            v-permission="'patient:query'"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="button-group">
        <el-button
          type="primary"
          v-permission="'patient:add'"
          @click="handleAdd"
        >
          <el-icon><Plus /></el-icon>新增病人
        </el-button>
      </div>
    </div>

    <!-- 病人表格 -->
    <el-table
      :data="insureList"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="insureName" label="姓名" width="120" />
      <el-table-column prop="idCard" label="身份证号" width="180" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column label="性别" width="80">
        <template #default="{ row }">
          <span>{{ row.sex === '1' ? '男' : '女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="nation" label="民族" width="80" />
      <el-table-column prop="birthDate" label="出生日期" width="120" />
      <el-table-column label="详细地址" min-width="180">
        <template #default="{ row }">
          <span>{{ formatAddress(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
            v-permission="'patient:edit'"
            size="small"
            @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            v-permission="'patient:delete'"
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form
        ref="insureForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="insureName">
          <el-input v-model="formData.insureName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="formData.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="formData.sex" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input v-model="formData.nation" placeholder="请输入民族" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="formData.birthDate"
            type="date"
            placeholder="选择出生日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="国家" prop="countryId">
          <el-select
            v-model="formData.countryId"
            placeholder="请选择国家"
            @change="handleCountryChange"
          >
            <el-option
              v-for="item in countries"
              :key="item.regionId"
              :label="item.regionName"
              :value="item.regionId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="省份" prop="provinceId">
          <el-select
            v-model="formData.provinceId"
            placeholder="请选择省份"
            @change="handleProvinceChange"
            :disabled="!formData.countryId"
          >
            <el-option
              v-for="item in provinces"
              :key="item.regionId"
              :label="item.regionName"
              :value="item.regionId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="城市" prop="cityId">
          <el-select
            v-model="formData.cityId"
            placeholder="请选择城市"
            @change="handleCityChange"
            :disabled="!formData.provinceId"
          >
            <el-option
              v-for="item in cities"
              :key="item.regionId"
              :label="item.regionName"
              :value="item.regionId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="区县" prop="districtId">
          <el-select
            v-model="formData.districtId"
            placeholder="请选择区县"
            @change="handleDistrictChange"
            :disabled="!formData.cityId"
          >
            <el-option
              v-for="item in districts"
              :key="item.regionId"
              :label="item.regionName"
              :value="item.regionId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="乡镇/街道" prop="townId">
          <el-select
            v-model="formData.townId"
            placeholder="请选择乡镇/街道"
            :disabled="!formData.districtId"
          >
            <el-option
              v-for="item in towns"
              :key="item.regionId"
              :label="item.regionName"
              :value="item.regionId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="详细地址" prop="addressDetail">
          <el-input
            v-model="formData.addressDetail"
            placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getInsureList,
  addInsure,
  updateInsure,
  deleteInsure,
  getRegionTree,
  getRegionsByParentId
} from '@/api/insure'

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  insureName: '',
  idCard: '',
  sex: ''
})

// 表格数据
const insureList = ref([])
const total = ref(0)
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)

// 表单数据
const formData = reactive({
  id: null,
  insureName: '',
  idCard: '',
  phone: '',
  sex: '1',
  nation: '',
  birthDate: '',
  countryId: null,
  provinceId: null,
  cityId: null,
  districtId: null,
  townId: null,
  addressDetail: ''
})

// 地区数据
const countries = ref([])
const provinces = ref([])
const cities = ref([])
const districts = ref([])
const towns = ref([])
const regionMap = ref({}) // 用于存储所有地区数据，方便查找

// 表单验证规则
const rules = reactive({
  insureName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern:
        /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
      message: '请输入正确的身份证号格式',
      trigger: 'blur'
    }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  countryId: [{ required: true, message: '请选择国家', trigger: 'change' }],
  addressDetail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
})

// 获取病人列表
const fetchInsureList = async () => {
  try {
    loading.value = true
    const res = await getInsureList(queryParams)
    insureList.value = res.data.data.records
    total.value = res.data.data.total
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.page = 1
  fetchInsureList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.insureName = ''
  queryParams.idCard = ''
  queryParams.sex = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchInsureList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.page = val
  fetchInsureList()
}

// 新增病人
const handleAdd = () => {
  dialogTitle.value = '新增病人'
  isAdd.value = true
  resetForm()
  dialogVisible.value = true
}

// 编辑病人
const handleEdit = (row) => {
  dialogTitle.value = '编辑病人'
  isAdd.value = false
  Object.assign(formData, row)
  loadRegionDataForEdit(row)
  dialogVisible.value = true
}

// 删除病人
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该病人信息吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await deleteInsure(row.id)
      ElMessage.success('删除成功')
      fetchInsureList()
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    insureName: '',
    idCard: '',
    phone: '',
    sex: '1',
    nation: '',
    birthDate: '',
    countryId: null,
    provinceId: null,
    cityId: null,
    districtId: null,
    townId: null,
    addressDetail: ''
  })
  provinces.value = []
  cities.value = []
  districts.value = []
  towns.value = []
}

// 提交表单
const submitForm = async () => {
  try {
    if (isAdd.value) {
      await addInsure(formData)
      ElMessage.success('新增成功')
    } else {
      await updateInsure(formData)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchInsureList()
  } catch (error) {
    console.error(error)
  }
}

// 格式化地址显示
const formatAddress = (row) => {
  const addressParts = []
  if (row.countryId && regionMap.value[row.countryId]) {
    addressParts.push(regionMap.value[row.countryId].regionName)
  }
  if (row.provinceId && regionMap.value[row.provinceId]) {
    addressParts.push(regionMap.value[row.provinceId].regionName)
  }
  if (row.cityId && regionMap.value[row.cityId]) {
    addressParts.push(regionMap.value[row.cityId].regionName)
  }
  if (row.districtId && regionMap.value[row.districtId]) {
    addressParts.push(regionMap.value[row.districtId].regionName)
  }
  if (row.townId && regionMap.value[row.townId]) {
    addressParts.push(regionMap.value[row.townId].regionName)
  }
  if (row.addressDetail) {
    addressParts.push(row.addressDetail)
  }
  return addressParts.join('')
}

// 加载地区数据
const loadRegionData = async () => {
  const res = await getRegionTree()
  countries.value = res.data.data.filter((region) => region.regionLevel === 1)

  // 构建地区映射表
  const allRegions = flattenRegions(res.data.data)
  allRegions.forEach((region) => {
    regionMap.value[region.regionId] = region
  })
}

// 扁平化地区树形结构
const flattenRegions = (regions) => {
  let result = []
  regions.forEach((region) => {
    result.push(region)
    if (region.children && region.children.length > 0) {
      result = result.concat(flattenRegions(region.children))
    }
  })
  return result
}

// 加载编辑时的地区数据
const loadRegionDataForEdit = async (row) => {
  if (row.countryId) {
    const countryRes = await getRegionsByParentId(row.countryId)
    provinces.value = countryRes.data.data
  }
  if (row.provinceId) {
    const provinceRes = await getRegionsByParentId(row.provinceId)
    cities.value = provinceRes.data.data
  }
  if (row.cityId) {
    const cityRes = await getRegionsByParentId(row.cityId)
    districts.value = cityRes.data.data
  }
  if (row.districtId) {
    const districtRes = await getRegionsByParentId(row.districtId)
    towns.value = districtRes.data.data
  }
}

// 国家变化事件
const handleCountryChange = async (countryId) => {
  formData.provinceId = null
  formData.cityId = null
  formData.districtId = null
  formData.townId = null
  cities.value = []
  districts.value = []
  towns.value = []

  if (countryId) {
    const res = await getRegionsByParentId(countryId)
    provinces.value = res.data.data
  } else {
    provinces.value = []
  }
}

// 省份变化事件
const handleProvinceChange = async (provinceId) => {
  formData.cityId = null
  formData.districtId = null
  formData.townId = null
  districts.value = []
  towns.value = []

  if (provinceId) {
    const res = await getRegionsByParentId(provinceId)
    cities.value = res.data.data
  } else {
    cities.value = []
  }
}

// 城市变化事件
const handleCityChange = async (cityId) => {
  formData.districtId = null
  formData.townId = null
  towns.value = []

  if (cityId) {
    const res = await getRegionsByParentId(cityId)
    districts.value = res.data.data
  } else {
    districts.value = []
  }
}

// 区县变化事件
const handleDistrictChange = async (districtId) => {
  formData.townId = null

  if (districtId) {
    const res = await getRegionsByParentId(districtId)
    towns.value = res.data.data
  } else {
    towns.value = []
  }
}

// 初始化加载数据
onMounted(() => {
  fetchInsureList()
  loadRegionData()
})
</script>

<style scoped>
.insure-management {
  padding: 20px;
}

.operation-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.button-group {
  margin-left: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-select {
  width: 100%;
}
</style>
